<script>
  import { createEventDispatcher } from "svelte";
  const dispatch = createEventDispatcher();
  const submit = () => dispatch("submit");

  let oldVal = "";
  let inputEle;
  export let value = "";
  export let placeholder = "";
  export let numeric = false;
  function onInputInner(payload) {
    let value = payload.target?.value;
    // console.log(value);
    if (numeric && value) {
      let digitFlag = false;
      if (value.endsWith(".")) {
        digitFlag = true;
        value = value.substring(0, value.length - 1);
      }
      const n = Number(value);
      if (isNaN(n) || (digitFlag && n % 1 !== 0) || value.endsWith(" ")) {
        // return;
        payload.target.value = oldVal;
        value = oldVal;
      }
    }
    submit();
  }
  function onClear() {
    value = "";
    inputEle.value = "";
    submit();
  }
</script>

<div class="tt-input w-72">
  <div class="tt-inner">
    <input
      type="text"
      bind:this={inputEle}
      class="tt-input-inner w-full h-full"
      placeholder={placeholder || "请输入"}
      bind:value
      on:input={onInputInner}
    />
    <button
      class="btn btn-xs btn-circle btn-outline grow"
      on:click={onClear}
      style={`transform: scale(0.5);
      visibility:${value ? "visible" : "hidden"}`}
    >
      x
    </button>
  </div>
</div>

<style>
  .tt-input {
    @apply input;
    @apply input-bordered;
    @apply max-w-xs;
    @apply input-primary;
    flex-shrink: 1;
  }
  .tt-input-lg {
    @apply input-lg;
  }
  .tt-input-md {
    @apply input-md;
  }
  .tt-input-sm {
    @apply input-sm;
  }
  .tt-input-disabled {
    @apply input-disabled;
    cursor: not-allowed;
  }
  .tt-input-disabled input {
    cursor: not-allowed;
  }
  .tt-inner {
    width: 100%;
    height: 100%;
    height: 3rem;
    display: flex;
    flex-direction: row;
    align-items: center;
  }
  .tt-input-inner {
    border: none;
    outline: none;
    background-color: transparent;
  }
  .tt-input:has(.tt-input-inner:focus) {
    @apply input-primary;
  }
  .tt-input.tt-input-success:has(.tt-input-inner:focus) {
    @apply input-success;
  }
  .tt-input.tt-input-warning:has(.tt-input-inner:focus) {
    @apply input-warning;
  }
  .tt-input.tt-input-info:has(.tt-input-inner:focus) {
    @apply input-info;
  }
  .tt-input.tt-input-error:has(.tt-input-inner:focus) {
    @apply input-error;
  }
</style>
